package com.woniuxy.dudugua.service.impl;

import com.woniuxy.dudugua.entity.Address;
import com.woniuxy.dudugua.entity.AddressExample;
import com.woniuxy.dudugua.entity.User;
import com.woniuxy.dudugua.mapper.AddressMapper;
import com.woniuxy.dudugua.service.AddressService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户地址管理的业务层
 */
@Service
public class AddressServiceImpl implements AddressService {
    @Resource
    private AddressMapper addressMapper;

    /**
     * 更新用户地址信息
     * @param address
     * @throws Exception
     */
    public void updateAddress(Address address) throws Exception {
        //先查询当前这个地址对象是否是默认地址，如果是，那么直接更新，如果不是，那么先将所有userid为这个的状态都更新为2，再更新当前对象
        if(addressMapper.selectByPrimaryKey(address.getId()).getStatus()==1){
            addressMapper.updateByPrimaryKeySelective(address);
        }else{
            AddressExample example = new AddressExample();
            example.createCriteria().andUserIdEqualTo(address.getUserId());
            //查询出来所有的订单对象
            List<Address> addresses = addressMapper.selectByExample(example);
            for(Address add:addresses){
                add.setStatus(2);
                addressMapper.updateByPrimaryKeySelective(add);
            }
            addressMapper.updateByPrimaryKeySelective(address);
        }
    }

    /**
     * 新增用户地址信息
     * @param address
     * @throws Exception
     */
    public void insertAddress(Address address) throws Exception {
        address.setId(null);
        //判断是否填了默认，如果status等于1，则更新所有该用户的默认地址状态，再添加
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(address.getStatus()==1){
            AddressExample example = new AddressExample();
            example.createCriteria().andUserIdEqualTo(user.getId());
            //查询出来所有的订单对象
            List<Address> addresses = addressMapper.selectByExample(example);
            for(Address add:addresses){
                add.setStatus(2);
                addressMapper.updateByPrimaryKeySelective(add);
            }
        }
        address.setUserId(user.getId());
        addressMapper.insertSelective(address);
    }

    @Override
    public Address selectDefaultAddress(int userid) {
        AddressExample e = new AddressExample();
        AddressExample.Criteria c = e.createCriteria();
        c.andUserIdEqualTo(userid);
        c.andStatusEqualTo(1);
        List<Address> list = addressMapper.selectByExample(e);
        return list.get(0);
    }
}
